<?php
/**
 * Created by PhpStorm.
 * User: lockie
 * Date: 2019/3/29
 * Time: 10:13
 */

namespace app\index\controller;

vendor('aliyun-oss-php-sdk.autoload','.php');

use OSS\Core\OssException;
use OSS\OssClient;
use think\Controller;

class Oss extends Controller
{
    private $_accessKeyId="LTAI8SvC2yPy2amW";
    private $_accessKeySecre="f0Y4S8o4xPbrUKN1zGXSQpDEzETomN";
    private $_endpoint="oss-cn-zhangjiakou.aliyuncs.com";
    private $_upimages='dayiimg';

    /**
     * 设置为公共读取
     */
    public function setBucket(){
        try {
            $ossClient = new OssClient($this->_accessKeyId, $this->_accessKeySecre, $this->_endpoint);
            // 设置存储空间的存储类型为低频访问类型，默认是标准类型。
            $options = array(
                OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA
            );
            $backet='dayiimg';
            // 设置存储空间的权限为公共读，默认是私有读写。
            $flg= $ossClient->createBucket($backet, OssClient::OSS_ACL_TYPE_PUBLIC_READ, $options);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * 上传图片
     * @return bool
     * @throws OssException
     */
    public function upimg(){
        if ($_FILES) {
            $err='';
            foreach ($_FILES as $value) {
                if(isset($value['error']) && is_array($value['error'])){
                    foreach ($value["error"] as $k => $v) {
                        if ($v == 1) {
                            echo $err = $value['name'][$k] . '超过了php.ini的upload_max_filesize最大上传文件大小';
                            return false;
                        } elseif ($v == 2) {
                            echo $err = $value['name'][$k] . '超过了浏览器表单的最大上传文件大小';
                            return false;
                        } elseif ($v == 3) {
                            echo $err = $value['name'][$k] . '上传的文件仅部分上传';
                            return false;
                        } elseif ($v == 4) {
                            echo $err = $value['name'][$k] . '没有上传文件';
                            return false;
                        } elseif ($v == 6) {
                            echo $err = $value['name'][$k] . '缺少系统临时文件夹或者无写入权限';
                            return false;
                        } elseif ($v == 7) {
                            echo $err = $value['name'][$k] . '系统错误，写入磁盘失败';
                            return false;
                        } elseif ($v == 8) {
                            echo $err = $value['name'][$k] . 'PHP扩展程序停止文件上传';
                            return false;
                        }
                    }
                }elseif($value['error']){
                    if ($value['error'] == 1) {
                        echo $err = $value['name'] . '超过了php.ini的upload_max_filesize最大上传文件大小';
                        return false;
                    } elseif ($value['error'] == 2) {
                        echo $err = $value['name']. '超过了浏览器表单的最大上传文件大小';
                        return false;
                    } elseif ($value['error'] == 3) {
                        echo $err = $value['name'] . '上传的文件仅部分上传';
                        return false;
                    } elseif ($value['error'] == 4) {
                        echo $err = $value['name'] . '没有上传文件';
                        return false;
                    } elseif ($value['error'] == 6) {
                        echo $err = $value['name'] . '缺少系统临时文件夹或者无写入权限';
                        return false;
                    } elseif ($value['error'] == 7) {
                        echo $err = $value['name'] . '系统错误，写入磁盘失败';
                        return false;
                    } elseif ($value['error'] == 8) {
                        echo $err = $value['name'] . 'PHP扩展程序停止文件上传';
                        return false;
                    }
                }
            }
            if($err){
                return json(['status'=>false,'msg'=>$err]);
            }
//            处理文件数组
            $bucketName = $this->_upimages;
            $ossClient = new OssClient($this->_accessKeyId, $this->_accessKeySecre, $this->_endpoint);
            if (is_null($ossClient)) {
                return json(['status'=>false,'msg'=>'oss对象获取失败!']);
            }
            $upload_root = 'image';//C('SERVERFILE_ROOT');
            $category = 'upload';
            $folder = "/{$category}/" . date('Ym/d', time());

            $upload_folder = $upload_root . $folder;

            $objectListing = $ossClient->createObjectDir($bucketName, $upload_folder); //创建目录,防止时间24点出现目录错误
            //upload_folder 注意要为 'zx/tt/ll',前后不要有/不然会出错
            if ($objectListing['info']['http_code'] != 200) {
                //myLog($objectListing, 'oss_log');
                return json(['status'=>false,'msg'=>'文件创建失败!']);
            }
            $filename = array();
            foreach ($_FILES as $value) {
                if(isset($value['tmp_name']) && is_array($value['tmp_name'])){
                    foreach ($value['tmp_name'] as $k => $v) {
                        $filename[$k]['name'] = $value['name'][$k];
                        $filename[$k]['local_path'] = $value['tmp_name'][$k];
                        $filename[$k]['folder'] = $upload_folder;
                        $filename[$k]['size'] = $value['size'][$k];
                        $filename[$k]['type'] = $value['type'][$k];
                        $des_name_suffix = substr(strrchr($value['name'][$k], '.'), 1);
                        $des_name = date('YmdHisx', microtime(true)) . rand(100, 999) . rand(10, 99);
                        $filename[$k]['file_name'] = $des_name . '.' . $des_name_suffix;
                        $filename[$k]['extension'] = $des_name_suffix;
                        $filename[$k]['destination_name'] = $bucketName . $filename[$k]['folder'] . $des_name . '.' . $des_name_suffix; //存储在OSS里面最后的名字
                    }
                }else{
                    $filename[0]['name'] = $value['name'];
                    $filename[0]['local_path'] = $value['tmp_name'];
                    $filename[0]['folder'] = $upload_folder;
                    $filename[0]['size'] = $value['size'];
                    $filename[0]['type'] = $value['type'];
                    $des_name_suffix = substr(strrchr($value['name'], '.'), 1);
                    $des_name = date('YmdHisx', microtime(true)) . rand(100, 999) . rand(10, 99);
                    $filename[0]['file_name'] = $des_name . '.' . $des_name_suffix;
                    $filename[0]['extension'] = $des_name_suffix;
                    $filename[0]['destination_name'] = $bucketName . $filename['folder'] . $des_name . '.' . $des_name_suffix; //存储在OSS里面最后的名字
                }
            }

            $return_array = array();
            foreach ($filename as $kk => $vv) {
                $return = $ossClient->uploadFile($bucketName, ($upload_folder . '/' . $vv['file_name']), $vv['local_path']);
                //($upload_folder . '/' . $vv['file_name'])注意这个目录一定要是 'zx/tt/ll',前后不要有/不然会出错
                if ($return['info']['http_code'] == 200) {
                    $return_array[$kk]['savename'] = $vv['file_name'];
                    $return_array[$kk]['type'] = $vv['type'];
                    $return_array[$kk]['size'] = $vv['size'];
                    $return_array[$kk]['extension'] = $vv['extension'];
                    $return_array[$kk]['savepath'] = '/' . $upload_folder . $vv['file_name'];
                    $return_array[$kk]['hash'] = $return['content-md5'];
                    $return_array[$kk]['oss_url'] = $return['info']['url'];
                } else {
                    //myLog($return, 'api_log');
                    $err = 'HTTP头部信息返回错误！';
                }
            }

            var_dump($filename);
            var_dump($return_array);die;
        }else{
            var_dump($_POST);
        }
    }

    /**
     * 上传图片
     * @return \think\response\Json
     * @throws OssException
     */
    public function uploadimg(){
        $scr = $_FILES['file']['tmp_name'];
        $ext = substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.')+1); // 上传文件后缀

        $dst = md5(time()).'-'.$scr.'.'.$ext;     //上传文件名称
        vendor('aliyun-oss-php-sdk.demo','.php');
        $updemo = new \demo();
        $url = $updemo->upload($dst,$scr);
        $data = array('url' =>$url);
        return json(['code'=>0,'data'=>$data]);

    }
}